<template>
    <div class="app-container">
        <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch"
                 label-width="90px">
            <el-form-item label="发布村社：" prop="communityId">
                <el-select v-model="queryParams.communityId" placeholder="请选择活动展示的村社或自然村" @change="changeCommunity" clearable>
                    <el-option
                        v-for="community in communityList"
                        :key="community.communityId"
                        :label="community.communityName"
                        :value="community.communityId"
                    ></el-option>
                </el-select>
            </el-form-item>
            <el-form-item label="活动标题" prop="title" clearable>
                <el-input
                    v-model="queryParams.title"
                    placeholder="请输入活动标题"
                    clearable
                    @keyup.enter.native="handleQuery"
                />
            </el-form-item>
            <el-form-item>
                <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
                <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
            </el-form-item>
        </el-form>

        <el-row :gutter="10" class="mb8">
            <el-col :span="1.5">
                <el-button
                    type="primary"
                    plain
                    icon="el-icon-plus"
                    size="mini"
                    @click="handleAdd"
                    v-hasPermi="['docs:activity:add']"
                >新增
                </el-button>
            </el-col>
            <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
        </el-row>

        <el-table v-loading="loading" :data="activityList" @selection-change="handleSelectionChange" border>
            <el-table-column type="selection" width="55" align="center"/>
            <el-table-column label="所属类目" align="center" prop="columnName"/>
            <el-table-column label="村社" align="center" prop="communityName"/>
            <el-table-column label="类型" align="center" width="150">
                <template slot-scope="scope">
                    <el-tag  type="danger" v-if="scope.row.type==0">线上参与</el-tag>
                    <el-tag v-if="scope.row.type==1">线下参与</el-tag>
                </template>
            </el-table-column>
            <el-table-column label="活动标题" align="left" prop="title" width="280" :show-overflow-tooltip="true"/>
            <el-table-column label="允许参与人数" align="center" prop="limitNumber" width="120"/>
            <el-table-column label="活动时间" align="center"  width="280">
                <template slot-scope="scope">
                    <span>{{parseTime(scope.row.expireStart,'{y}-{m}-{d}')}} ~ {{parseTime(scope.row.expireEnd,'{y}-{m}-{d}')}}</span>
                </template>
            </el-table-column>
            <el-table-column label="报名时间" align="center"  width="280">
                <template slot-scope="scope" v-if="scope.row.type==1">
                    <span>{{parseTime(scope.row.bookingStart,'{y}-{m}-{d}')}} ~ {{parseTime(scope.row.bookingEnd,'{y}-{m}-{d}')}}</span>
                </template>
            </el-table-column>

            <el-table-column label="奖励积分" align="center" prop="score"/>
            <el-table-column label="状态" align="center" prop="status">
                <template slot-scope="scope">
                    <el-switch
                        v-model="scope.row.status"
                        active-value="0"
                        inactive-value="1"
                        @change="handleStatusChange(scope.row)"
                    ></el-switch>
                </template>
            </el-table-column>
            <el-table-column label="操作" align="center" class-name="small-padding fixed-width" fixed="right" width="200">
                <template slot-scope="scope">
                    <el-button
                        size="mini"
                        type="text"
                        icon="el-icon-edit"
                        @click="handleUpdate(scope.row)"
                        v-hasPermi="['docs:activity:edit']"
                    >修改
                    </el-button>
                    <el-button
                        v-if="scope.row.type===1"
                        size="mini"
                        type="text"
                        icon="el-icon-download"
                        @click="generateQrcode(scope.row)"
                        v-hasPermi="['docs:activity:query']"
                    >下载签到码
                    </el-button>
                </template>
            </el-table-column>
        </el-table>

        <pagination
            v-show="total>0"
            :total="total"
            :page.sync="queryParams.pageNum"
            :limit.sync="queryParams.pageSize"
            @pagination="getList"
        />

        <!-- 添加或修改活动列表对话框 -->
        <el-dialog :title="title" :visible.sync="open" width="800px" append-to-body>
            <el-form ref="form" :model="form" :rules="rules" label-width="100px">
                <el-form-item label="活动标题：" prop="title">
                    <el-input v-model="form.title" placeholder="请输活动标题"/>
                </el-form-item>
                <el-form-item label="活动类目：" prop="columnId">
                    <treeselect v-model="form.columnId" :options="columnOptions" @select="treeSelectChange"
                                :show-count="true" placeholder="请选择归属活动类目"/>
                </el-form-item>
                <el-form-item label="发布村社：" prop="communityId">
                    <el-select v-model="form.communityId" placeholder="请选择活动展示的村社或自然村" @change="changeCommunity" :disabled="form.communityIdShow">
                        <el-option
                            v-for="community in communityList"
                            :key="community.communityId"
                            :label="community.communityName"
                            :value="community.communityId"
                        ></el-option>
                    </el-select>
                </el-form-item>
<!--                <el-form-item label="轮播展示：" prop="carousel">-->
<!--                    <el-radio-group v-model="form.isCarousel">-->
<!--                        <el-radio :key="type.label" :label="type.label" v-for="type in carousels">{{ type.name }}</el-radio>-->
<!--                    </el-radio-group>-->
<!--                </el-form-item>-->
                <el-form-item label="活动类型：" prop="type" @change="handleType">
                    <el-radio-group v-model="form.type">
                        <el-radio :key="type.label" :label="type.label" v-for="type in types">{{ type.name }}</el-radio>
                    </el-radio-group>
                </el-form-item>

                <el-form-item label="活动图片：" prop="imgUrl">
                    <image-upload v-model="form.imgUrl" :limit="1"  :fileSize="1"/>
                </el-form-item>
                <el-form-item label="活动时间：" prop="expireStart">
                    <el-col :span="20">
                        <el-date-picker
                            v-model="expireDate.date"
                            type="datetimerange"
                            range-separator="至"
                            value-format="yyyy-MM-dd HH:mm:ss"
                            start-placeholder="活动开始时间"
                            end-placeholder="活动结束时间"  :default-time="['00:00:00', '23:59:59']" @change="expireDateFormat">
                        </el-date-picker>
                    </el-col>
                </el-form-item>
                <el-form-item label="奖励积分：" prop="score">
                    <el-input v-model="form.score" placeholder="请输入参与活动获取的积分数" style="width:400px"/>
                </el-form-item>

                <el-form-item label="报名时间：" prop="bookingStart" v-if="form.type==1">
                    <el-col :span="20">
                        <el-date-picker
                            v-model="bookingDate.date"
                            type="datetimerange"
                            range-separator="至"
                            value-format="yyyy-MM-dd HH:mm:ss"
                            start-placeholder="活动开始时间"
                            end-placeholder="活动结束时间"  :default-time="['00:00:00', '23:59:59']" @change="bookDateFormat">
                        </el-date-picker>
                    </el-col>
                </el-form-item>
                <el-form-item label="参与人数：" prop="score" v-if="form.type==1">
                    <el-input v-model="form.limitNumber" placeholder="参与人数" style="width:400px"/>
                </el-form-item>
                <el-form-item label="活动地址：" prop="score" v-if="form.type==1">
                    <el-input v-model="form.address" placeholder="活动地址"/>
                </el-form-item>
                <el-form-item label="活动内容：" prop="content">
                    <editor v-model="form.content" :min-height="200" :fileSize="1"/>
                </el-form-item>

            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button type="primary" @click="submitForm">确 定</el-button>
                <el-button @click="cancel">取 消</el-button>
            </div>
        </el-dialog>
    </div>
</template>

<script>
import {listActivity, getActivity, delActivity, addActivity, updateActivity,changeActivityStatus} from "@/api/docs/activity";
import store from "@/store/index";
import {listCommunity} from "@/api/organization/community";
import Treeselect from "@riophae/vue-treeselect";
import {columnTree} from "@/api/docs/article";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";
import {communityPermission} from "@/utils/ruoyi";
export default {
    name: "Activity",
    components: {Treeselect},
    data() {
        return {
            token:store.getters.token,
            communityIdShow:false,
            expireDate:{
                date:[],
                expire_start:'',
                expire_end:'',
            },
            bookingDate:{
                date:[],
                booking_start:'',
                booking_end:'',
            },
            columnOptions: undefined,
            // 遮罩层
            loading: true,
            // 选中数组
            ids: [],
            // 非单个禁用
            single: true,
            // 非多个禁用
            multiple: true,
            // 显示搜索条件
            showSearch: true,
            // 总条数
            total: 0,
            // 活动列表表格数据
            activityList: [],
            communityList: [],
            // 弹出层标题
            title: "",
            // 是否显示弹出层
            open: false,
            querycommunityParams:{
                pageNum: 1,
                pageSize: 100,
                status:0
            },
            // 查询参数
            queryParams: {
                pageNum: 1,
                pageSize: 10,
                title: null,
                columnId: null,
                communityId: null,
                content: null,
                imgUrl: null,
                visit: null,
                shares: null,
                times: null,
                score: null,
                status: null,
                isTop: null,
                expireStart: null,
                expireEnd: null,
            },
            queryColumn:{
                pageNum: 1,
                pageSize: 10,
                columnType:1
            },
            types:[{'name':'线上参与','label':0},{'name':'线下参与','label':1}],
            carousels:[{'name':'否','label':0},{'name':'是','label':1}],
            // 表单参数
            form: {},
            // 表单校验
            rules: {
                title: [{required: true, message: "活动标题不能为空", trigger: "blur"}],
                communityId: [{required: true, message: "活动显示村社不能空", trigger: "blur"}],
                columnId: [{required: true, message: "活动显示的栏目", trigger: "blur"}],
                imgUrl: [{required: true, message: "活动缩略图不能空", trigger: "blur"}],
                expireStart: [{required: true, message: "信息有效期不能空", trigger: "blur"}],
                score: [{required: true, message: "奖励积分", trigger: "blur"}],
                content: [{required: true, message: "活动内容不能为空", trigger: "blur"}],
            }
        };
    },
    created() {

        this.getList();
        this.listCommunityOptions();
        this.getColumnTree();
    },
    methods: {
        listCommunityOptions() {
            listCommunity(this.querycommunityParams).then(resp => {
                this.communityList = resp.rows;
            })
        },
        handleType(label) {
            this.form.type = label;
        },
        treeSelectChange(raw, instanceId) {
            if (raw.children != undefined && raw.children.length > 0) {
                this.$modal.alertError("请选择发布的子栏目");
            }
            this.form.columnName = raw.label;
        },
        changeCommunity(raw) {
            console.log('changeCommunity')
            for (let communityListElement of this.communityList) { console.log(communityListElement)
                if(communityListElement.communityId==raw) {
                    this.form.communityName = communityListElement.communityName;
                    break;
                }
            }

        },
        /** 查询栏目信息列表 */
        getColumnTree() {
            columnTree(1).then(response => {
                this.columnOptions = response.data;
                this.loading = false;
            });
        },
        /** 查询活动列表列表 */
        getList() {
            this.loading = true;
            listActivity(this.queryParams).then(response => {
                this.activityList = response.rows;
                this.total = response.total;
                this.loading = false;
            });
        },
        expireDateFormat(expire) {
            this.form.expireStart =expire[0].toString();
            this.form.expireEnd = expire[1].toString();
        },
        bookDateFormat(expire) {
            this.form.bookingStart =expire[0].toString();
            this.form.bookingEnd = expire[1].toString();
        },

        // 取消按钮
        cancel() {
            this.open = false;
            this.reset();
        },
        // 表单重置
        reset() {
            this.form = {
                activityId: null,
                title: null,
                columnId: null,
                columnName: null,
                communityId: null,
                communityName: null,
                content: null,
                imgUrl: null,
                visit: null,
                shares: null,
                times: null,
                score: null,
                status: null,
                isTop: null,
                expireStart: null,
                expireEnd: null,
                bookingStart: null,
                bookingEnd: null,
                createBy: null,
                createTime: null,
                updateBy: null,
                updateTime: null,
                type:0,
                communityIdShow:false,
                isCarousel:0
            };
            this.resetForm("form");
            this.expireDate.date = [];
            this.bookingDate.date = [];
        },
        /** 搜索按钮操作 */
        handleQuery() {
            this.queryParams.pageNum = 1;
            this.getList();
        },
        /** 重置按钮操作 */
        resetQuery() {
            this.resetForm("queryForm");
            this.handleQuery();
        },
        // 多选框选中数据
        handleSelectionChange(selection) {
            this.ids = selection.map(item => item.activityId)
            this.single = selection.length !== 1
            this.multiple = !selection.length
        },
        /** 新增按钮操作 */
        handleAdd() {
            this.reset();
            this.open = true;
            this.title = "添加活动";
            this.form.type=0;
            // this.form.communityId = store.getters.communityId;
            this.communityIdShow = communityPermission(this.form,this.communityIdShow);
            console.log(this.form);
        },
        /** 修改按钮操作 */
        handleUpdate(row) {
            this.reset();
            const activityId = row.activityId || this.ids
            getActivity(activityId).then(response => {
                this.form = response.data;
                this.open = true;
                this.title = "修改活动";
                this.expireDate.date = [];
                this.bookingDate.date = [];
                this.expireDate.date.push(this.form.expireStart);
                this.expireDate.date.push(this.form.expireEnd);
                if (this.form.bookingStart != null && this.form.bookingEnd != null) {
                    this.bookingDate.date.push(this.form.bookingStart);
                    this.bookingDate.date.push(this.form.bookingEnd);
                }
            });
        },
        /** 提交按钮 */
        submitForm() {
            this.$refs["form"].validate(valid => {
                if (valid) {
                    if (this.form.activityId != null) {
                        updateActivity(this.form).then(response => {
                            this.$modal.msgSuccess("修改成功");
                            this.open = false;
                            this.getList();
                        });
                    } else {
                        addActivity(this.form).then(response => {
                            this.$modal.msgSuccess("新增成功");
                            this.open = false;
                            this.getList();
                        });
                    }
                }
            });
        },
        /** 删除按钮操作 */
        handleDelete(row) {
            const activityIds = row.activityId || this.ids;
            this.$modal.confirm('是否确认删除活动列表编号为"' + activityIds + '"的数据项？').then(function () {
                return delActivity(activityIds);
            }).then(() => {
                this.getList();
                this.$modal.msgSuccess("删除成功");
            }).catch(() => {
            });
        },
        /** 导出按钮操作 */
        handleExport() {
            this.download('docs/activity/export', {
                ...this.queryParams
            }, `activity_${new Date().getTime()}.xlsx`)
        },
        handleStatusChange(row) {
            let text = row.status === "0" ? "启用" : "禁用";
            this.$modal.confirm('确认要"' + text + row.title + '这个活动嘛？').then(function () {
                return changeActivityStatus(row.activityId, row.status);
            }).then(() => {
                this.$modal.msgSuccess(text + "成功");
            }).catch(function () {
                row.status = row.status === "0" ? "1" : "0";
            });
        },
      /** 活动二维码 */
      generateQrcode(row) {
        this.download('/docs/activity/createQrcode/'+row.activityId,{}, `活动`+ row.title +`的二维码_${new Date().getTime()}.jpg`)
      }
    }
};
</script>
